package com.wangshidai.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wangshidai.entity.SysRole;
import com.wangshidai.entity.SysRolePermission;
import com.wangshidai.enums.RoleEnum;
import com.wangshidai.enums.RolePermissionEnum;
import com.wangshidai.mapper.SysRolePermissionMapper;
import com.wangshidai.reply.rolereply.QueryRoleNameReply;
import com.wangshidai.service.SysRoleService;
import com.wangshidai.mapper.SysRoleMapper;
import com.wangshidai.util.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 *
 */
@Slf4j
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService{
    @Autowired
    private SysRoleMapper sysRoleMapper;
    @Autowired
    private SysRolePermissionMapper sysRolePermissionMapper;
    @Override
    public boolean queryRoleName(Page<QueryRoleNameReply> page, String name) {
        long total = sysRoleMapper.queryRoleName(page, name).getTotal();
        log.info("模糊查询到{}条数据",total);
        if(total<1){
            return false;
        }
        return true;
    }
    @Override
    public boolean insertRole(SysRole role) throws BusinessException {
        log.info("尝试新建角色{}",role);
        QueryWrapper wrapper = new QueryWrapper<>();
        wrapper.eq(RoleEnum.NAME, role.getName());
        long count = sysRoleMapper.selectCount(wrapper);
        if (count>= 1) {
            throw new BusinessException("角色名称已存在！");
        }
        count = sysRoleMapper.insert(role);
        if (count<1) {
            throw new BusinessException("角色在数据库创建失败，原因未知！");
        }
        log.info("角色创建成功");
        return true;
    }

    @Override
    public boolean alterRole(SysRole role) throws BusinessException {
        log.info("角色修改为{}",role);
        QueryWrapper wrapper = new QueryWrapper<>();
        wrapper.eq(RoleEnum.NAME, role.getName());
        wrapper.ne(RoleEnum.ID,role.getId());
        long count = sysRoleMapper.selectCount(wrapper);
        if (count>= 1) {
            throw new BusinessException("角色名称已存在！");
        }
        count= sysRoleMapper.updateById(role);
        if (count<1) {
            throw new BusinessException("角色在数据库修改失败，原因未知！");
        }
        log.info("角色修改成功");
        return true;
    }

    @Override
    public boolean deleteRoleById(long id) {
        QueryWrapper<SysRolePermission> wrapper = new QueryWrapper<>();
        wrapper.eq(RolePermissionEnum.ROLE_ID, id);
        sysRolePermissionMapper.delete(wrapper);
        log.info("权限删除成功");
        log.info("开始删除角色");
        return sysRoleMapper.deleteById(id)==1;
    }
}




